#!/bin/sh

TRACK_FILE=${HOME}/.local/share/${USER}/.track

timestamp () {
    # extract timestamp from track file line format
    echo $@ | awk '{ print $1; }'
}

task () {
    # extract task from track file line format
    echo $@ | awk '{ print $2; }'
}

convert () {
    # print unix timestamp as hour:minute
    echo -n "$(date +"%H:%M" --date "@$1")"
}

timespan () {
    [ $# -lt 2 ] && echo "timespan called with less than 2 arguments"

    # calculate hours and minutes
    minutes=$(echo "($2 - $1) / 60" | bc)
    hours=$(echo "$minutes / 60" | bc)
    minutes=$(echo "$minutes - ($hours * 60)" | bc)

    # set strings for printing
    hours="$hours h, "
    minutes="$minutes min"

    # print start and end in hour:minute format
    echo -n "$(convert $1) - $(convert $2)"
    # shift out two timestamps and print rest (task)
    shift; shift; echo " $@ ($hours$minutes)"
}

[ -n "$1" ] && today="$1" || today=$(date +"%Y-%m-%d")

# initial timestamp is set to beginning of "today"
start=$(date +%s --date "$today")
task="new beginning"

# iterate lines
IFS="
"
for line in $(grep "$today" ${TRACK_FILE}); do
    # extract new end time
    end=$(timestamp $line)

    # calculate timespan since last time and current time
    timespan $start $end $task

    # set new start as old end time
    start=$end

    # carry over task into the next iteration
    # this makes sense because the semantics of a tracked line is to denote
    # when one begins an activity as such the time associated with the
    # activity is not only the last activity's end time, but the new
    # activity's start time
    task=$(task $line)
done

# print a last task (with changed semantics: only start of the last activity
# of the day)
echo "        $(convert $start) $task"
